package gcontent.entities.site;

import gcontent.config.PersistentConfig;
import gcontent.config.persistents.node.ObjectNode;
import gcontent.entities.Site;
import gcontent.entities.content.error.ContentEx;
import gcontent.entities.content.html.RefHTML;
import gcontent.launch.SpiderThread;
import gcontent.record.db.RecordDB;
import gcontent.record.error.RecordEx;
import gcontent.rsrc.ThreadResources;

import java.net.URL;
import java.util.ArrayList;

public class SiteURL extends Site{

	protected URL url;
	
	public SiteURL()
	{	
		super();
	}
	
	public SiteURL(URL url)
	{
		this.url = url;
		this.protocol = url.getProtocol();
	}
	
	public void saveTMP() throws ContentEx, RecordEx 
	{	
		ObjectNode obj_node;
		int port;

		port = this.url.getPort();
		if(port == -1)
			port = this.url.getDefaultPort();
		
		obj_node = PersistentConfig.getConfPerClass(this.getClass().getName());
		if(obj_node == null)
			throw new RecordEx("not persistent config for class " +  this.getClass().getName());
		
		this.id_tmp = (Integer)this.record.execProc("PROC_CreateRefURLTMP",
							this.id,
							obj_node.getId(),
							this.url.getHost(),
							port,
							this.url.toString()
							);						
	}	
	
	public static SiteURL getTMP(String host, int port) throws ContentEx, RecordEx
	{
		RecordDB record;
		ArrayList<SiteURL> ret_site;
		
		record = (RecordDB)((SpiderThread)ThreadResources.getResource(ThreadResources.RSRC.SPIDER)).getRecord();
		
		ret_site = (ArrayList<SiteURL>)record.getObject("PROC_GetRefTmpByDomain",
				host,
				port
				);	
		
		if(ret_site.size() > 0)
			return ret_site.get(0);
		
		return null;
	}
	
	public void setURL(String url)
	{
		try { 
			this.url = new URL(url);
		} catch(Exception ex) {
			this.url = null;
		}
	}
		
	/* url destination */
	public URL getURL()
	{
		return this.url;
	}
}
